
class Agent(object):
    
    NAME = "KR1702_agent"
    ammo_pos = []
    agent_goal=[0,0,0,0,0,0]
    my_CP = [0,0]
    agent_ammo=[0,0,0,0,0,0]


    def __init__(self, id, team, settings=None, field_rects=None, field_grid=None, nav_mesh=None):
        """ Each agent is initialized at the beginning of each game.
            The first agent (id==0) can use this to set up global variables.
            Note that the properties pertaining to the game field might not be
            given for each game.
        """
        self.id = id
        self.team = team
        self.mesh = nav_mesh
        self.grid = field_grid
        self.settings = settings
        self.goal = None
        
        #global my_CP
        #self.my_CP=


        # Read the binary blob, we're not using it though
        #blob=open('probs.txt','r')
        #if blob is not None:
            #print "Agent %s-%d received binary blob of %s" % (
                #('BLU' if team else 'RED'), id, type(pickle.loads(blob.read())))
            # Reset the file so other agents can read it.
            #blob.seek(0) 
        
        # Recommended way to share variables between agents.
        
        #if id == 0:
           # self.all_agents = self.__class__.all_agents #= []
        #print 'help',self.__class__.all_agents
        #self.all_agents.append(self)




    
    def observe(self, observation):
        """ Each agent is passed an observation using this function,
            before being asked for an action. You can store either
            the observation object or its properties to use them
            to determine your action. Note that the observation object
            is modified in place.
        """
        self.observation = observation
        self.selected = observation.selected

        
    def action(self):
        """ This function is called every step and should
            return a tuple in the form: (turn, speed, shoot)
        """
        obs = self.observation
        global ammo_pos
        global agent_goal
        global agent_ammo

        #make the amount of ammo global knowledge
        self.__class__.agent_ammo[self.id]=obs.ammo


        print obs
        # Check if agent reached goal.
        if self.goal is not None and point_dist(self.goal, obs.loc) < self.settings.tilesize:
            self.goal = None


        # Walk to ammo always you see it
        ammopacks = filter(lambda x: x[2] == "Ammo", obs.objects)
        already=False
        if ammopacks:
            self.goal = ammopacks[0][0:2]
            self.id
            if len(self.__class__.ammo_pos) ==0:
                self.ammo_pos.append(ammopacks[0][0:2])
            elif len(self.__class__.ammo_pos) <4:
                for x in self.__class__.ammo_pos:
                    if x== ammopacks[0][0:2]:
                        already = True
                if already == False:
                    self.ammo_pos.append(ammopacks[0][0:2])
            print self.__class__.ammo_pos
        
            
        # Drive to where the user clicked
        if self.selected and self.observation.clicked:
            self.goal = self.observation.clicked


        #are you in the range of your CP
        if math.sqrt((obs.loc[0]-obs.cps[self.id%3][0])**2+(obs.loc[1]-obs.cps[self.id%3][1])**2) < 5:
            self.__class__.agent_goal[self.id]=1 # I am in range of my CP
        else:
            self.__class__.agent_goal[self.id]=0 # I am NOT in range of my CP
        
        # Walk to your CP, schrijf twee versies: even en oneven id
        # gebruik modulo 4%3=1
        range = 20
        if self.goal is None:
            if obs.cps[self.id%3][2] != 0:
                self.goal = obs.cps[self.id%3][0:2]
            else:
                if self.__class__.agent_goal[(self.id+3)%6] == 1 and self.__class__.agent_ammo[self.id] < self.__class__.agent_ammo[(self.id+3)%6]: #kijk naar je buddy
                    # go to CP range
                    self.goal = [obs.cps[0][0]+random.randint(-range,range), obs.cps[0][1]+random.randint(-range,range)]
                else:
                    if len(self.__class__.ammo_pos) > 0:
                        self.goal=self.__class__.ammo_pos[random.randint(0,len(self.__class__.ammo_pos)-1)]
                    else:
                        print "You should explore the world and find ammo"


        # Shoot enemies
        shoot = False
        if (obs.ammo > 0 and 
            obs.foes and 
            point_dist(obs.foes[0][0:2], obs.loc) < self.settings.max_range
            and not line_intersects_grid(obs.loc, obs.foes[0][0:2], self.grid, self.settings.tilesize)):
            self.goal = obs.foes[0][0:2]
            shoot = True

        # Compute path, angle and drive
        #print 'before', self.grid
        path = find_path(obs.loc, self.goal, self.mesh, self.grid, self.settings.tilesize)
        if path:
            dx = path[0][0]-obs.loc[0]
            dy = path[0][1]-obs.loc[1]
            turn = angle_fix(math.atan2(dy, dx)-obs.angle)
            if turn > self.settings.max_turn or turn < -self.settings.max_turn:
                shoot = False
            speed = (dx**2 + dy**2)**0.5
        else:
            turn = 0
            speed = 0
        #print turn
        #if math.fabs(turn)>math.pi/6:
            #speed=0
        return (turn,speed,shoot)
        
    def debug(self, surface):
        """ Allows the agents to draw on the game UI,
            Refer to the pygame reference to see how you can
            draw on a pygame.surface. The given surface is
            not cleared automatically. Additionally, this
            function will only be called when the renderer is
            active, and it will only be called for the active team.
        """
        import pygame
        pygame.draw.circle(surface,(0,0,0),(328,328),10,2)
        # First agent clears the screen
        if self.id == 0:
            surface.fill((0,0,0,0))
        
        # Selected agents draw their info
        if self.selected:
            if self.goal is not None:
                pygame.draw.line(surface,(0,0,0),self.observation.loc, self.goal)
        
    def finalize(self, interrupted=False):
        """ This function is called after the game ends, 
            either due to time/score limits, or due to an
            interrupt (CTRL+C) by the user. Use it to
            store any learned variables and write logs/reports.
        """
        pass
        
